<template>
  <Drawer :visible="props.showModal" width="600" :closable="false">
    <template #title>
      <div class="title-header">{{ `${props.title}设备` }}</div>
    </template>

    <template #extra> <CloseOutlined @click="modalCancelFn" /></template>

    <template #footer>
      <div style="display: flex; justify-content: center">
        <Button style="margin-right: 50px" @click="modalCancelFn">取消</Button>
        <Button type="primary" @click="modalOkFn">保存</Button>
      </div>
    </template>

    <Form :model="state.data" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" ref="formRef">
      <a-form-item label="设备类型" name="deviceId">
        <Select v-model:value="state.data.deviceId" :disabled="props.title === '修改'" style="width: 200px">
          <SelectOption :value="0">普通冰箱</SelectOption>
          <SelectOption :value="1">自动化设备</SelectOption>
        </Select>
      </a-form-item>

      <a-form-item label="关联测点" name="postId">
        <Select v-model:value="state.data.postId" mode="multiple" :disabled="props.title === '修改'" style="width: 200px" :options="state.pointList" />
      </a-form-item>

      <a-form-item label="设备名称" name="levelName">
        <Input v-model:value="state.data.levelName" style="width: 200px" />
      </a-form-item>

      <a-form-item label="设备图片" name="image">
        <div style="display: flex">
          <Upload :show-upload-list="false" :beforeUpload="beforeUpload" :custom-request="customRequestFn">
            <div class="upload-img-box">
              <img v-if="state.imgURL" :src="state.imgURL" alt="" />
              <PlusOutlined v-else style="font-size: 30px; color: #8b8b9e" />
            </div>
          </Upload>
          <div style="margin: 10px; color: red">{{ '格式要求：jpg、png，<200k' }}</div>
        </div>
      </a-form-item>

      <a-form-item v-if="state.data.deviceId === 0" label="结构" name="level">
        <Row>
          <Col :span="7">
            <InputNumber v-model:value="state.data.level" :min="1" :max="6" addon-after="级" :disabled="props.title === '修改'" />
          </Col>
          <span style="color: red; margin-left: 10px; line-height: 30px"> 注意：设备结构最多不可超过6级 </span>
        </Row>
      </a-form-item>

      <Table v-if="state.data.deviceId === 0" :data-source="state.tableList" :columns="columns" :pagination="false" style="padding: 0 10px 10px" size="small" bordered>
        <template #bodyCell="{ column, text, record }">
          <div v-if="column['dataIndex'] === 'index'" style="width: 50px">{{ text }}</div>

          <a-input v-else-if="column['dataIndex'] === 'levelName'" v-model:value="record['levelName']" :disabled="record.disabled" style="width: 70px" placeholder="名称" />

          <div v-else-if="column['dataIndex'] === 'serialArr'" style="display: flex">
            <a-input v-model:value="record['serialArr'][0]" style="width: 80px" placeholder="编码前段" />
            <InputNumber v-model:value="record['serialArr'][1]" style="width: 80px; margin: 0 10px" :min="1" :max="20" placeholder="编号位数" />
            <a-input v-model:value="record['serialArr'][2]" style="width: 80px" placeholder="编码后段" />
          </div>

          <InputNumber v-else v-model:value="record[column['dataIndex']]" :disabled="props.title === '修改'" :min="1" style="width: 70px" placeholder="数量" />
        </template>
      </Table>

      <a-form-item v-if="props.title === '新增'" label="最大单盒孔位数量" name="maxCapacity">
        <InputNumber v-model:value="state.data.maxCapacity" style="width: 200px" :min="0" />
      </a-form-item>

      <a-form-item v-if="state.data.deviceId !== 0 && props.title === '新增'" label="选择配置文件" name="deviceInfo">
        <Upload :show-upload-list="false" :beforeUpload="beforeDispositionUpload" :custom-request="dispositionCustomRequestFn">
          <Button type="white-blue">文件上传</Button>
        </Upload>
        <div style="color: #95b2f9; margin-top: 10px">{{ state.excelName }}</div>
      </a-form-item>

      <template v-if="state.data.deviceId === 0">
        <h4 style="margin-left: 10px">层级示意图</h4>
        <div style="display: flex; justify-content: center">
          <Tabs v-model:activeKey="state.activeKey" centered style="width: 600px; margin-bottom: 30px">
            <TabPane key="1" tab="冰箱">
              <img src="@/assets/images/save-box.png" alt="" />
            </TabPane>
            <TabPane key="2" tab="液氮罐" force-render>
              <img src="@/assets/images/box-ice.jpg" alt="" />
            </TabPane>
          </Tabs>
        </div>
      </template>
    </Form>
  </Drawer>
</template>

<script setup lang="ts">
import { message, Form, Input, Upload, Row, Col, Tabs, TabPane, Table, InputNumber, Drawer, Modal, Select, SelectOption } from 'ant-design-vue';
import { reactive, ref, watch } from 'vue';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue';
import Button from '@/framework/components/basic/button/button.vue';
import { addEquipment, addTripartiteEquipment, editEquipment, editTripartiteEquipmentById, getPoint, getStorage, uploadExcel } from '@/modules/underlying-data/api/storage-managment';
import { uploadFile } from '@/api/public';

/**
 * const
 */
const props = withDefaults(
  defineProps<{
    showModal?: boolean;
    data: any;
    title: string;
    freezerBoxId: number;
  }>(),
  {
    showModal: false,
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'editModalOk'): void;
}>();
const state: {
  data: any;
  imgURL: any;
  excelName: string;
  activeKey: string;
  tableList: any[];
  pointList: any[];
} = reactive({
  data: {},
  imgURL: '',
  excelName: '',
  activeKey: '1',
  tableList: [],
  pointList: [],
});
const formRef = ref();
const rules = {
  deviceId: [{ required: true, message: '数据必填!' }],
  levelName: [{ required: true, message: '数据必填!' }],
  image: [{ required: true, message: '数据必填!' }],
  level: [{ required: true, message: '数据必填!' }],
  maxCapacity: [{ required: true, message: '数据必填!' }],
  deviceInfo: [{ required: true, message: '数据必填!' }],
  postId: [{ required: true, message: '数据必填!' }],
};
const columns = [
  {
    title: '层级',
    dataIndex: 'index',
    width: '20%',
    align: 'center',
  },
  {
    title: '名称',
    dataIndex: 'levelName',
    width: '20%',
    align: 'center',
  },
  {
    title: '编码规则',
    dataIndex: 'serialArr',
    width: '40%',
    align: 'center',
  },
  {
    title: '数量',
    dataIndex: 'capacity',
    width: '20%',
    align: 'center',
  },
];

/**
 * watch
 */
// 初始化
watch(
  () => props.showModal,
  async () => {
    if (!props.showModal) return;
    await getPointFn();
    if (props.title === '修改') {
      columns.length === 4 && columns.pop();
      const res = await getStorage(props.data?.storageId);
      state.data = res.result;
      state.data.level = res.result?.layers;
      if (res.result.deviceId === 0) {
        state.tableList = res.result?.storageList?.map((item, index) => ({
          index: index + 1,
          levelName: item.levelName,
          serialArr: [item.serialPrefix, item.serial, item.serialSuffix],
          capacity: item.capacity,
        }));
        state.tableList[state.tableList?.length - 1].disabled = true;
      } else {
        state.data.deviceId = 1;
      }
      state.imgURL = props.data?.url;
    } else {
      columns.length === 3 &&
        columns.push({
          title: '数量',
          dataIndex: 'capacity',
          width: '15%',
          align: 'center',
        });
      state.data = {};
      state.data.deviceId = 0;
    }
  },
);
// 生成表格结构信息
watch(
  () => state.data?.level,
  () => {
    if (props.title === '修改') return;
    state.tableList = [];
    for (let i = 0; i < state.data.level; i++) {
      let obj: any = {
        index: i + 1,
        levelName: '',
        serialArr: ['', '', ''],
        capacity: '',
      };
      if (i === state.data.level - 1) {
        obj.disabled = true;
        obj.levelName = '盒位';
      }
      state.tableList.push(obj);
    }
  },
);

/**
 * data
 */
const getPointFn = async () => {
  const res = await getPoint();
  state.pointList = res.result.map((item) => ({
    label: item.name,
    value: item.id,
  }));
};
/**
 * fn
 */
const modalOkFn = async () => {
  // 验证
  try {
    await formRef.value?.validateFields();
  } catch {
    return;
  }
  if (state.tableList.map((item) => item.serialArr[1]).some((item) => !item)) {
    return message.warn('编码规则不符合要求，编码位数为必填项！');
  }
  const modal = Modal.confirm({
    title: '保存设备信息时间较长，请耐心等待！',
    onOk: async () => {
      let ids = Object.values(state.data?.postId);
      if (state.data?.deviceId === 0) {
        // 自有设备
        let params: any[] = [
          {
            levelName: state.data?.levelName,
            image: state.data?.image,
            type: 2,
          },
          ...state.tableList.map((item) => ({
            capacity: item.capacity,
            levelName: item.levelName,
            serialPrefix: item.serialArr[0],
            serialSuffix: item.serialArr[2],
            serial: item.serialArr[1],
            type: item.index + (item.index >= 6 ? 3 : 2),
          })),
        ];
        params[params.length - 1].type = 8;
        if (props.title === '新增') {
          params[params.length - 1].maxCapacity = state.data?.maxCapacity;
          params[0].parentId = props.freezerBoxId;
          params[0].postId = ids.join();
          params[0].postName = ids.map((item) => state.pointList.find((sub) => sub?.value === item)?.label).join();
          console.log(params);
          await addEquipment(params);
        } else {
          params[0].storageId = state.data.id;
          await editEquipment(params);
        }
      } else {
        let params;
        if (props.title === '新增') {
          params = {
            levelName: state.data?.levelName,
            parentId: props.freezerBoxId,
            image: state.data?.image,
            maxCapacity: state.data?.maxCapacity,
            deviceInfo: state.data?.deviceInfo,
            postId: ids.join(),
            postName: ids.map((item) => state.pointList.find((sub) => sub?.value === item)?.label).join(),
          };
          await addTripartiteEquipment(params);
        } else {
          params = {
            name: state.data?.levelName,
            image: state.data?.image,
          };
          await editTripartiteEquipmentById(props.data?.storageId, params);
        }
      }
      message.success('操作成功！');
      emits('editModalOk');
      modalCancelFn();
      modal.destroy();
    },
  });
};
const modalCancelFn = () => {
  formRef.value?.resetFields();
  state.data = {};
  state.imgURL = '';
  state.excelName = '';
  state.tableList = [];
  emits('update:showModal', false);
};

/**
 * 图片上传
 */
const customRequestFn = async (e) => {
  const reader = new FileReader();
  reader.readAsDataURL(e.file);
  reader.addEventListener('load', () => {
    state.imgURL = reader.result;
  });
  const formData = new FormData();
  formData.append('file', e.file);
  const res = await uploadFile(formData);
  state.data.image = res.result.md5;
  e.onSuccess();
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('仅允许jpg、png格式图片!');
  }
  const isLt200K = file.size / 1024 < 200;
  if (!isLt200K) {
    message.error('文件大小应小于200k!');
  }
  return isJpgOrPng && isLt200K;
};

/**
 * 配置文件上传
 */
const dispositionCustomRequestFn = async (e) => {
  const formData = new FormData();
  formData.append('file', e.file);
  const res = await uploadExcel(formData);
  state.excelName = e?.file?.name;
  state.data.deviceInfo = res.result;
  e.onSuccess();
};
const beforeDispositionUpload = () => {
  return true;
};
</script>

<style scoped lang="less">
.upload-img-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 105px;
  height: 114px;
  border: 1px solid #cecece;
  > img {
    object-fit: contain;
  }
}
</style>
